package com.xiaolin.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaolin.admin.constants.AvailableConstant;
import com.xiaolin.admin.exception.ServiceException;
import com.xiaolin.admin.mapper.SysUserMapper;
import com.xiaolin.admin.model.dto.CurrentUser;
import com.xiaolin.admin.model.dto.UserLoginInfo;
import com.xiaolin.admin.model.entity.SysUser;
import com.xiaolin.admin.service.AuthService;
import com.xiaolin.admin.service.SysMenuService;
import com.xiaolin.admin.service.SysRoleService;
import com.xiaolin.admin.utils.ContextUtil;
import com.xiaolin.admin.utils.RedisUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.UUID;

/**
 * @author xiaolin
 * @description 描述
 * @since 2024/7/25
 */
@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysMenuService menuService;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private ContextUtil contextUtil;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public String login(UserLoginInfo userLoginInfo) {
        // 校验用户是否存在
        SysUser user = userMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserAccount, userLoginInfo.getUsername()));
        if (Objects.isNull(user)) {
            ServiceException.error("用户不存在");
        }
        // 校验用户是否禁用
        if(AvailableConstant.DISABLE.equals(user.getAvailable())) {
            ServiceException.error("用户已禁用");
        }
        // 校验密码是否正确
        if (!user.getUserPassword().equals(DigestUtils.md5Hex(userLoginInfo.getPassword()))) {
            ServiceException.error("密码错误");
        }
        CurrentUser currentUser = new CurrentUser();
        BeanUtils.copyProperties(user, currentUser);
        String token = UUID.randomUUID().toString();
        redisUtil.set(token, currentUser, 30 * 60);
        return token;
    }

    @Override
    public CurrentUser info(HttpServletRequest request) {
        CurrentUser currentUser = contextUtil.getCurrentUser();
        // 获取用户角色
        currentUser.setRoles(roleService.getUserRoles());
        // 获取用户接口权限
        currentUser.setApiPermission(menuService.getUserApiPermissions());
        // 刷新用户信息
        contextUtil.refreshLoginStatus(currentUser, 30 * 60);
        // 获取用户模块权限
        currentUser.setMenuPermissions(menuService.getUserMenuPermissions());
        return currentUser;
    }

    @Override
    public boolean logout(HttpServletRequest request) {
        contextUtil.removeLoginStatus();
        return true;
    }
}
